<template>
  <div>
    <el-row>
      <el-col :offset="1" :span="11">
        <el-card style="padding:40px 40px 20px 20px; height: 82vh;overflow: auto;">
          <el-table :data="cellList" style="width: 100%"  v-loading="loading">
            <el-table-column prop="name" label="所属小区" width="180"></el-table-column>
            <el-table-column label="编辑">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  icon="el-icon-delete"
                  type="danger"
                  @click="remove(scope.row)"
                  style="margin:5px 0 0 0"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :offset="1" :span="10">
        <el-card style="padding:40px 40px 20px 20px; height: 82vh">
          <el-form
            ref="form"
            :model="model"
            @submit.native.prevent="save"
            label-width="100px"
            style="max-width: 800px;"
          >
            <el-form-item label="新建小区">
              <el-input v-model="model.name" required clearable placeholder="(例) 中关村"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" native-type="submit">立即创建</el-button>
              <el-button @click="cancel" :plain="true">取消</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  data() {
    return {
      model: {
        name: null
      },
      cellList: null,
      loading: true
    };
  },
  mounted() {
    this.fetch();
  },
  methods: {
    cancel() {
     this.model = {}
    },
    //获取列表
    async fetch() {
      const cell_list = await this.$http.get("rest/cell_list");
      this.cellList = cell_list.data;
      this.loading = false;
    },
    async save() {

      let flag = this.cellList.every( (item) => {
        return (item.name != this.model.name);
      });
      
      if (flag) {
        const response = await this.$http.post("rest/add_cell", this.model);
        this.model = {}
        this.fetch();

        this.$message({
          type: "success",
          message: "保存成功",
          duration: 2000
        });
      } else {
        this.$message({
          type: "warning",
          message: "已存在该小区",
          duration: 2000
        });
      }
    },
    //删除
    remove(row) {
      this.$confirm(`是否删除?"${row.name}"`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        await this.$http.delete(`rest/cell/${row._id}`);
        this.$message({
          type: "success",
          message: "删除成功!"
        });

        this.fetch();
      });
    }
  }
};
</script>

<style lang="less" scoped>
</style>